package com.ziyueyuwen.xiniao.controller.homework;

import com.ziyueyuwen.xiniao.base.HttpResContent;
import com.ziyueyuwen.xiniao.bean.homework.ZyHomeworkRecordDO;
import com.ziyueyuwen.xiniao.bean.homework.ZySubjectQuestionDO;
import com.ziyueyuwen.xiniao.bean.vo.ZyLessonVO;
import com.ziyueyuwen.xiniao.service.HomeworkRecordService;
import com.ziyueyuwen.xiniao.service.LessonService;
import com.ziyueyuwen.xiniao.service.SubjectQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;

import static com.ziyueyuwen.xiniao.base.BaseUtil.checkParam;
import static com.ziyueyuwen.xiniao.util.ConstUtil.*;

/**
 * @author jun 2018/12/20.
 */
@Controller
@RequestMapping("/homework/record")
public class HomeworkRecordController {

    @Autowired
    private SubjectQuestionService subjectQuestionService;

    @Autowired
    private LessonService lessonService;

    @Autowired
    private HomeworkRecordService homeworkRecordService;

    @RequestMapping(value = "/get_homework_record.do", method = RequestMethod.POST)
    public void getHomeworkRecord(@RequestParam(PARAM_LESSON_ID) Integer lessonId,
                                  @RequestParam(PARAM_SUBJECT_ID) Integer subjectId,
                                  @RequestParam(PARAM_HOMEWORK_INDEX) Integer homeworkIndex) throws Exception {
        HttpResContent<ZyHomeworkRecordDO> hrc = new HttpResContent<>("获取作业记录");
        // check.
        checkParam(PARAM_LESSON_ID, lessonId);
        checkParam(PARAM_SUBJECT_ID, subjectId);
        checkParam(PARAM_HOMEWORK_INDEX, homeworkIndex);
        // do.
        String studentId = hrc.getUserInfo().getUserAccount();
        ZySubjectQuestionDO zySubjectQuestion = subjectQuestionService.getBySubjectIdAndHomeworkIndex(subjectId, homeworkIndex);
        ZyHomeworkRecordDO ret = homeworkRecordService.getByStudentIdAndLessonId(studentId, lessonId);
        if (ret == null) {
            ret = new ZyHomeworkRecordDO();
            ZyLessonVO zyLessonVO = lessonService.getClassAndCourseByLessonId(lessonId);
            if (zyLessonVO == null) {
                throw new Exception("获取作业所属的班级和课节信息失败!");
            }
            ret.setClassId(zyLessonVO.getClassId());
            ret.setLessonId(lessonId);
            ret.setCourseId(zyLessonVO.getCourse().getId());
            ret.setStudentId(studentId);
            ret.setSubjectQuestionId(zySubjectQuestion.getId());
            ret.setAnswerInfoList(new ArrayList<>());
            ret.setIfFinishAnswer(false);
            ret.setIfMarked(false);
            if (!homeworkRecordService.add(ret)) {
                throw new Exception("初始化作业记录失败!");
            }
        }
        hrc.printLogAndResponse(ret);
    }

}
